import 'dart:convert';

import 'package:better_player/better_player.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_tv/vod_rated_route.dart';

import 'data_loader.dart';
import 'full_screen_route.dart';
import 'video_series.dart';

class DetailPlay extends StatefulWidget {
  final int vid;
  final int tid;

  DetailPlay({required this.vid, required this.tid});

  @override
  State<StatefulWidget> createState() => _DetailPlayState();
}

class _DetailPlayState extends State<DetailPlay> {
  late Future<Map<String, dynamic>?> _data;
  final DataLoader dataLoader = DataLoader();
  late BetterPlayerController _controller;
  final SwiperController _swiper_controller = new SwiperController();
  String _url = '';
  String _name = '';
  int _tid = 0;
  bool full_screen = false;
  int from_index = -1;
  int play_index = 1;
  int related_index = -1;
  List<Map<String, List<String>>> _voFromViews = [];

  @override
  void initState() {
    _data = dataLoader.loadVideoInfo(vid: widget.vid);
    BetterPlayerControlsConfiguration controlsConfiguration =
        BetterPlayerControlsConfiguration(
      playerTheme: BetterPlayerTheme.cupertino,
          enableFullscreen: false,
          enableMute: false,
          enableOverflowMenu: false,
          enableSkips: false,
    );

    BetterPlayerConfiguration betterPlayerConfiguration =
        BetterPlayerConfiguration(
      aspectRatio: 16 / 9,
      fit: BoxFit.contain,
      autoDispose: true,
      controlsConfiguration: controlsConfiguration,
    );

    _controller = BetterPlayerController(betterPlayerConfiguration);
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    _swiper_controller.dispose();
    super.dispose();
  }

  void prettyJsonString(list) {
    String jsonString = jsonEncode(list);
    JsonEncoder encoder = JsonEncoder.withIndent('  ');
    String prettyJsonString = encoder.convert(jsonDecode(jsonString));
    final pattern = RegExp('.{1,800}');
    pattern
        .allMatches(prettyJsonString)
        .forEach((match) => print(match.group(0)));
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Map<String, dynamic>?>(
      future: _data,
      builder: (BuildContext context,
          AsyncSnapshot<Map<String, dynamic>?> snapshot) {
        if (snapshot.connectionState == ConnectionState.done &&
            snapshot.hasData) {
          var data = snapshot.data!;
          _tid = data['type_id'];
          var vod_blurb = data['vod_blurb'];
          var videoName = data['vod_name'];
          var voFromName = data['vod_play_from'].split('\$\$\$');
          var voFromUrl = data['vod_play_url'].split('\$\$\$');
          var index = ((data['vod_play_note'].length / 3).toInt()) - 1;
          from_index = index <= 0 ? 0 : index;

          Set<String> voSet = Set<String>.from(voFromName);
          voFromName = voSet.toList();
          _voFromViews = List.generate(voFromName.length,
              (i) => VideoSeries.generate(_tid, voFromUrl, i));
          Map<String, List<String>> high_light_series =
              _voFromViews[from_index];
          List<String>? names = high_light_series['names'];
          List<String>? urls = high_light_series['urls'];

          _url = urls!.first;
          _name = '${videoName}.共 ${names!.length} 集';
          var vod_class = '类 型 :  ${data['vod_area']}.${data['vod_class']}';
          var vod_director = '导 演 :  ${data['vod_director']} ';
          var vod_actor = '演 员 :  ${data['vod_actor']}';
          print('\n\n===uri $_url ====  \n\n ');
          return MaterialApp(
            home: Scaffold(
              body: ListView(
                children: <Widget>[
                  Container(
                    color: Colors.black87,
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Expanded(
                              flex: 5,
                              child: Padding(
                                padding: const EdgeInsets.fromLTRB(
                                    20.0, 10.0, 8.0, 0.0),
                                child: Column(
                                  children: [
                                    align_text(_name,25),
                                    SizedBox(height: 5),
                                    align_text(vod_class,12),
                                    SizedBox(height: 2),
                                    align_text(vod_director,12),
                                    SizedBox(height: 5),
                                    align_text(vod_actor,12),
                                    SizedBox(height: 5),
                                    vod_blurb_name(vod_blurb),
                                    SizedBox(height: 8),
                                    vod_full_screen_button(),
                                  ],
                                ),
                              ),
                            ),
                            Expanded(flex: 5, child: vod_player()),
                          ],
                        ),
                        Container(
                          color: Color(0xFF282334),
                          child: Padding(
                            padding:
                                const EdgeInsets.fromLTRB(20.0, 0.0, 8.0, 0.0),
                            child: Column(
                              children: [
                                vod_series_card(voFromName),
                                vod_series_view(voFromName, urls, names),
                                SizedBox(height: 8),
                                vod_series_short(voFromName, names),
                                SizedBox(height: 18),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          color: Color(0xFF1A2037),
                          child: Padding(
                            padding:
                                const EdgeInsets.fromLTRB(20.0, 0.0, 8.0, 0.0),
                            child: Column(
                              children: [
                                vod_related_title(),
                                SizedBox(height: 5),
                                VodRelatedView(data: data, tid: widget.tid)
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        } else {
          return Container(
            color: Colors.white,
            constraints: const BoxConstraints.expand(),
            child: const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
              ),
            ),
          );
          ;
        }
      },
    );
  }

  Widget  align_text(String text,double fontSize){
    return Align(
      alignment: Alignment.topLeft,
      child: Text(
        text,
        style: TextStyle(
          fontSize: fontSize,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      ),
    );
  }

  Widget vod_blurb_name(vod_blurb) {
    return Text(
      vod_blurb,
      overflow: TextOverflow.ellipsis,
      maxLines: 3,
      style: TextStyle(
        fontSize: 12,
        fontWeight: FontWeight.bold,
        color: Colors.white,
      ),
    );
  }

  Widget vod_full_screen_button() {
    return Focus(
        onKey: (FocusNode node, RawKeyEvent event) {
          if (event.logicalKey == LogicalKeyboardKey.select) {
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(builder: (context) => FullScreen(url: _url)),
              (route) => true,
            );
            return KeyEventResult.handled;
          }
          return KeyEventResult.ignored;
        },
        onFocusChange: (focused) => setState(() {
              full_screen = focused ? true : false;
            }),
        child: Align(
          alignment: Alignment.centerLeft,
          child: SizedBox(
            width: 120,
            child: InkWell(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.orangeAccent.withOpacity(0.7),
                  border: Border.all(
                    color: full_screen ? Colors.deepOrange : Colors.transparent,
                    width: 3,
                    style: BorderStyle.solid,
                  ),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(1.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.stop,
                        color: Colors.white,
                        size: 50,
                      ),
                      Text(
                        '全屏',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ));
  }

  Widget vod_player() {
    BetterPlayerDataSource dataSource =
        BetterPlayerDataSource(BetterPlayerDataSourceType.network, _url);
    _controller.setupDataSource(dataSource);
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: BetterPlayer(controller: _controller),
    );
  }

  Widget vod_series_card(List<String> voFromName) {
    return Container(
      child: Row(
        children: List.generate(
          voFromName.length,
          (i) => focusCard(i, voFromName),
        ),
      ),
    );
  }

  Widget vod_series_view(voFromName, _urls, _names) {
    var padding = Padding(
      padding: EdgeInsets.only(left: 20, right: 20, bottom: 0, top: 5),
      child: Container(
        height: 40,
        child: Swiper(
          itemCount: voFromName.length,
          itemBuilder: (BuildContext context, int i) => ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: _names.length,
            itemBuilder: (context, index) {
              return Padding(
                padding: EdgeInsets.only(right: 15.0),
                child: Container(
                  width: 120,
                  child: focusButton(index, _names[index], _urls[index]),
                ),
              );
            },
          ),
          loop: false,
          controller: _swiper_controller,
        ),
      ),
    );
    return padding;
  }

  Widget vod_series_short(voFromName, _names) {
    int short_len = _names.length ~/ 10;
    short_len = short_len < 1 ? 1 : short_len;
    List<List<int>> groups = [];
    for (int i = 0; i < _names.length; i += 10) {
      groups.add([i + 1, i + 10]);
    }
    return Padding(
      padding: EdgeInsets.only(left: 20, right: 20, bottom: 0, top: 5),
      child: Container(
        height: 40,
        child: Swiper(
          itemCount: voFromName.length,
          itemBuilder: (BuildContext context, int i) => ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: groups.length,
            itemBuilder: (context, i) {
              return Padding(
                padding: EdgeInsets.only(right: 15.0),
                child: Container(
                  width: 90,
                  child: focusButtonShort(groups[i], i),
                ),
              );
            },
          ),
          loop: false,
          controller: _swiper_controller,
        ),
      ),
    );
  }

  Widget focusCard(index, tabs) {
    return Focus(
      onFocusChange: (focused) => setState(() {
        from_index = focused ? index : 0;
        _swiper_controller.move(index);
      }),
      child: Padding(
        padding: EdgeInsets.only(left: 20, right: 20, bottom: 0, top: 0),
        child: Align(
          child: Container(
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: from_index == index
                      ? Colors.orangeAccent.withOpacity(0.8)
                      : Colors.transparent,
                  width: 3,
                  style: BorderStyle.solid,
                ),
              ),
            ),
            child: Text(
              tabs[index],
              style: TextStyle(
                fontSize: 26,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget focusButton(int index, String name, String url) {
    name = [3, 26, 25].contains(widget.tid) ? '  $name  ' : name;
    return Focus(
      onFocusChange: (focused) => setState(() {
        play_index = focused ? index : play_index;
      }),
      child: InkWell(
        child: Container(
          decoration: BoxDecoration(
            border: Border.all(
              color: Color(0xFF313146),
              width: 3,
              style: BorderStyle.solid,
            ),
          ),
          alignment: Alignment.center,
          child: Padding(
            padding: const EdgeInsets.all(1.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Transform.rotate(
                  angle: 1.5,
                  child: Icon(
                    Icons.segment_outlined,
                    color: play_index == index
                        ? Colors.yellowAccent
                        : Colors.transparent,
                  ),
                ),
                Text(
                  name.replaceAll("集", '').replaceAll("第", ''),
                  style: TextStyle(
                    color: play_index == index
                        ? Colors.yellowAccent
                        : Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget focusButtonShort(List<int> range, int shortIndex) {
    return Focus(
      onFocusChange: (focused) => setState(() {}),
      child: InkWell(
        child: Container(
          decoration: BoxDecoration(
            border: Border.all(
              color: Color(0xFF313146),
              width: 3,
              style: BorderStyle.solid,
            ),
          ),
          alignment: Alignment.center,
          child: Padding(
            padding: const EdgeInsets.all(1.0),
            child: Text(
              '${range[0]}-${range[1]} ',
              style: TextStyle(
                color: play_index ~/ 10 == shortIndex
                    ? Colors.yellowAccent
                    : Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget vod_related_title() {
    return Align(
      alignment: Alignment.topLeft,
      child: Text(
        '看了还会看',
        style: TextStyle(
          fontSize: 25,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      ),
    );
  }
}
